package com.example.security.jwt;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class JwtFilter extends GenericFilter {
    private final Logger log = LoggerFactory.getLogger(JwtFilter.class);

    public static final String AUTHORIZATION_HEADER="Authorization";
    private TokenProvider tokenProvider;

    public JwtFilter(TokenProvider tokenProvider){
        this.tokenProvider = tokenProvider;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 获取 验证Token, 验证成功获取认证对象
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

       String jwtToken = resolveToken(httpServletRequest);
       if(StringUtils.hasText(jwtToken) && tokenProvider.validateToken(jwtToken)){

           Authentication authentication = tokenProvider.getAuthentication(jwtToken);
           SecurityContextHolder.getContext().setAuthentication(authentication);
       }else{
           log.warn("没有Token 请求路径:"+httpServletRequest.getRequestURI());
       }

        chain.doFilter(request,response);

    }

    /**
     * 从Header 获取Token
     * @param httpServletRequest
     * @return
     */
    private String resolveToken(HttpServletRequest httpServletRequest) {

        String header = httpServletRequest.getHeader(AUTHORIZATION_HEADER);
        if(StringUtils.hasText(header) && header.startsWith("Bearer")){
            return header.substring(7);
        }
        return null;
    }
}
